package com.starblink.android.basic.imgpreload

import android.graphics.drawable.Drawable
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.starblink.android.basic.ext.toBean
import com.starblink.android.basic.ext.toJson
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.network.base.BaseApiClient
import com.starblink.basic.storage.SkStorage
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.Md5Util
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.rocketreserver.fragment.ResourceF
import java.security.MessageDigest


/**
 * 图片预加载策略
 */
object PreloadResImgUtils {

    private const val SUFFIX_VERSION = "_151_1"

    //启动页
    const val LAUNCH_PAGE = "LAUNCH_PAGE$SUFFIX_VERSION"

    //首页广告
    const val HOME_ADVERT = "HOME_ADVERT$SUFFIX_VERSION"

    fun imgPreload(resF: ResourceF, type: String) {
        Glide.with(CommUtils.getContext()).load(resF.mainPic!!)
            .diskCacheStrategy(
                DiskCacheStrategy.DATA
            ).listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    YYLogUtils.e("-------->preload 预加载 ${type}失败")
                    return true
                }

                override fun onResourceReady(
                    resource: Drawable?,
                    model: Any?,
                    target: Target<Drawable>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    pollSaveHomeImg(resF, type)
                    if (BaseApiClient.getCurrSvrCfgEnvName() != "pub") {
                        toast("图片预加载成功")
                    }
                    return true
                }
            }).preload()
    }


    /**
     * 获取一张预加载图片 并删除缓存 后续弹出策略再进行扩展
     */
    fun popOneResourceF(type: String): ResourceF? {
        var resF: ResourceF? = null
        try {
            //获取对应type类型的新的资源的json字符串的MD5的set集合
            val setData: PreResImgData = getRealSetData(type)
            for (md5 in setData.typeReadySet) {
                resF = setData.resFMap[md5]
                if (resF != null) {
                    setData.typeReadySet.remove(md5)
                    setData.resFMap.remove(md5)
                    SkStorage.put(type, setData.toJson())
                    break
                }
            }

            resF?.let { sf ->
                //开始时间
                if (sf.startTime != null) {
                    var start: Long = -1

                    if (sf.startTime is Double) {
                        start = (sf.startTime as Double).toLong()
                    }
                    if (sf.startTime is Long) {
                        start = (sf.startTime as Long)
                    }
                    if (start > 0 && System.currentTimeMillis() < start) {
                        return null
                    }
                }
                //结束时间
                if (sf.endTime != null) {
                    var end: Long = -1
                    if (sf.endTime is Double) {
                        end = (sf.endTime as Double).toLong()
                    }
                    if (sf.endTime is Long) {
                        end = (sf.endTime as Long)
                    }
                    if (end > 0 && end < System.currentTimeMillis()) {
                        return null
                    }
                }
            }
        } catch (e: Exception) {
            YYLogUtils.e("preload 预加载 pop------>${e.message}")
            return null
        }
        return resF
    }

    /**
     * 判断是否还有缓存  还有缓存 是不重新请求接口的
     */
    fun cacheIsEmpty(type: String): Boolean {
        return getRealSetData(type).typeReadySet.isEmpty()
    }


    /**
     * 预加载图片
     */
    fun pollSaveHomeImg(resF: ResourceF, type: String) {
        resF.mainPic?.let { url ->
            val md = Md5Util.md5(url)
            val allSetData: PreResImgData = getRealSetData(type)
            YYLogUtils.e("preload 预加载 ")
            if (allSetData.typeAllSet.add(md)) {
                if (allSetData.typeReadySet.add(md)) {
                    allSetData.resFMap[md] = resF
                    SkStorage.put(type, allSetData.toJson())
                }
                if (allSetData.typeAllSet.size > 20) {
                    SkStorage.remove(type)
                }
            }
        }
    }

    private fun getRealSetData(type: String): PreResImgData {
        val allSetDataString = SkStorage.getString(type, null)
        val allSetData: PreResImgData = if (allSetDataString == null) {
            PreResImgData(type, hashSetOf(), hashSetOf(), hashMapOf())
        } else {
            allSetDataString.toBean()
        }
        return allSetData
    }

}